package net.huashitong.supervision.insideDuCha.service;

import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.service.SysTableService;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.supervision.insideDuCha.dao.InsideMainTaskDao;
import net.huashitong.supervision.insideDuCha.entity.InsideMainTaskEntity;
import net.huashitong.supervision.insideDuCha.entity.InsideSubTaskEntity;
import net.huashitong.supervision.insideDuCha.entity.InsideUserTaskEntity;
import net.huashitong.supervision.insideDuCha.filter.InsideMainTaskFilter;
import net.huashitong.supervision.insideDuCha.filter.InsideSubTaskFilter;
import net.huashitong.supervision.insideDuCha.filter.InsideUserTaskFilter;
import net.huashitong.supervision.insideDuCha.util.CommUtil;
import net.huashitong.supervision.task.entity.TaskBackNew;
import net.huashitong.supervision.task.entity.TaskPermissions;
import net.huashitong.supervision.task.service.SMSUtilService;
import net.huashitong.supervision.task.service.TaskBackNewService;
import net.huashitong.supervision.task.service.TaskLogNewService;
import net.huashitong.supervision.task.service.TaskPermissionService;
import net.huashitong.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class InsideMainTaskService extends StringPKService<InsideMainTaskEntity> {
    @Autowired
    private InsideMainTaskDao dao ;
    @Autowired
    private SysTableService sysTableService;

    @Autowired
    private TaskLogNewService taskLogService;

    @Autowired
    private TaskBackNewService taskBackService;

    @Autowired
    private InsideSubTaskService insideSubTaskService;
    @Autowired
    private InsideUserTaskService userTaskService;
    @Autowired
    private InsideCycleService cycleService;
    @Autowired
    private SMSUtilService smsUtilService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private TaskPermissionService tpService;

    @Override
    protected BaseDao<InsideMainTaskEntity, String> getDao() {
        return dao;
    }

    @Override
    protected void beforeSave(InsideMainTaskEntity obj) {
        obj.setSysId(sysTableService.updateMaxSysId("inside_task_main",null));

    }

    public void save(InsideMainTaskEntity entity,String createId)
    {

        beforeSave(entity);
        entity.setCreateDate(DateUtil.getCurrentDate());
        entity.setCreateTime(DateUtil.getCurrentTime());
        entity.setCreateUser(createId);
        dao.save(entity);

    }


    /**内部立项 创建
     * 创建任务，立项
     * @param filter
     */
    @Transactional
    public List<InsideSubTaskFilter> saveTask(InsideMainTaskFilter filter)
    {
        InsideMainTaskEntity entity = saveMainTask(filter);
        List<InsideSubTaskFilter> filters = insideSubTaskService.saveSubTasks(entity, filter.getInsideSubTasks());
//        List<InsideSubTaskFilter> listsubs = insideSubTaskService.saveSubTasks(entity, filters);
        List<InsideSubTaskFilter> listSubs = userTaskService.saveUsetTasks(filters);
        //短信提醒
        sendMessage(listSubs,entity.getTaskName());

        //短信提醒自定义的领导
        if(filter.getSendLeader()==1){
//            sendToLeader();
            List<TaskPermissions> listLeader = tpService.getListLeader(filter.getDeptId(), 2);
            sendToLeader(entity.getTaskName(),filter.getDeptId());
        }

        return listSubs;
    }

    //自定义领导短信
    private  void sendToLeader(String taskMainName,String deptId){

        List<TaskPermissions> listLeader = tpService.getListLeader(deptId, 2);
        String content = "-单位内部任务《"+taskMainName+"》，已立项派发成功，";
        String msg = "【督查管理系统】您好，督查事项" +  content+ "相关详情请登陆系统查看";
        for (TaskPermissions leader : listLeader) {
            SysUser user = userService.getById(leader.getUserId());
            String mobile = user.getMobile();
            String realName = user.getName();
            smsUtilService.taskLeaderMessage(mobile,realName,msg);
        }
    }


    //发送短信
    private void sendMessage(List<InsideSubTaskFilter> listSubs,String taskMainName){
        for (InsideSubTaskFilter sub : listSubs) {
            String userIdStr = sub.getUserId();
            String[] userIdArry = userIdStr.split(",");//分割多选人员；
            for (String userId : userIdArry) {
                SysUser user = userService.getById(userId);
                String mobile = user.getMobile();
                String name = user.getName();
                String taskName = taskMainName+"-"+sub.getSubTaskName();
                smsUtilService.taskUnitMessage(taskName,mobile,name);
            }
        }
    }


    /**
     * 保存 主任务
     * @param filter
     * @return
     */
    public InsideMainTaskEntity saveMainTask(InsideMainTaskFilter filter){
        InsideMainTaskEntity entity = new InsideMainTaskEntity();

        String deptId =filter.getDeptId();
        if(StringUtils.isBlank(deptId))
        {
            deptId= SysUserUtils.getDeptId();
        }
        entity.setDeptId(deptId);
        entity.setTaskCont(filter.getTaskCont());
        entity.setTaskName(filter.getTaskName());
        entity.setDeptId(filter.getDeptId());

        entity.setValids(filter.getValids());
        entity.setTimeAging(1+"");
        entity.setTaskState("0");
        //处理时限
        String[] timeTypes = CommUtil.changeTimeType(filter.getTimeType(), filter.getPeriod(),
                filter.getDay(), filter.getWeek(), filter.getMonth(),
                filter.getQuarter(), filter.getTimeLimit(), filter.getTimeLimits());

        if("0".equals(timeTypes[0])){
            return  null;
        }

        entity.setTimeType(Integer.parseInt(timeTypes[0]));
        entity.setCycleValue(timeTypes[1]);
        System.out.println("主任务时间类型"+entity.getTimeType());
        System.out.println("主任务循环值" + entity.getCycleValue());
        if(StringUtils.isBlank(SysUserUtils.getUserId()))
        {
            save(entity,filter.getLoginerId());
        }else {

            this.save(entity);
        }
        return entity;
    }


    /**
     * 反馈
     * @param filter
     * @return
     */
    public  TaskBackNew saveFreebackTasks(InsideSubTaskFilter filter)
    {
        //backtype /任务状态(0.待签收,1待反馈,2已反馈,3退回,4完成 。5已签收)
        String loginId = SysUserUtils.getUserId();
        TaskBackNew entity = new TaskBackNew();

        InsideSubTaskEntity subTask = insideSubTaskService.getById(filter.getSysId());
        InsideUserTaskFilter userTaskFilter = new InsideUserTaskFilter();
        userTaskFilter.setSubTaskId(subTask.getSysId());
        userTaskFilter.setUserId(loginId);
        List<InsideUserTaskFilter> userlist = userTaskService.getUserlist(userTaskFilter);
        InsideUserTaskFilter userTask = userlist.get(0);

        entity.setStatus("3");
        entity.setTaskUnitId(userTask.getSysId());
        entity.setTaskMainId(subTask.getTaskMainId());
        entity.setTaskSubId(subTask.getSysId());//人员任务id
        entity.setUserName(userTask.getUserName());
        entity.setContent(filter.getSituations());
        entity.setProblem(filter.getProblems());
        entity.setPlan(filter.getNextPlan());
        entity.setFileName(filter.getFileName());
        entity.setFile(filter.getFileIds());
        entity.setDeptType("5");  //1 牵头， 2 协办 ，3 督办单位；4 攻坚任务 5 内部
        entity.setDel(null);

        taskBackService.save(entity,loginId);
        //反馈后主任务 和子任务 装填更新为 新反馈

        InsideMainTaskEntity main = this.getById(subTask.getTaskMainId());
        main.setBackType("1");
        main.setTaskState("2");
        this.update(main);

        //subTask.setBackType("1");
        subTask.setTaskState("2");//2在办  type /任务状态(0.待签收,1待反馈,2已反馈,3退回,4完成 。5已签收)
        insideSubTaskService.update(subTask);

        InsideUserTaskEntity userTaskEntity = userTaskService.getById(userTask.getSysId());
        userTaskEntity.setTaskState("2"); //type /任务状态(0.待签收,1待反馈,2已反馈,3退回,4完成 。5已签收)
        userTaskService.update(userTaskEntity);


        return  entity;

    }


    /**
     * 获取主任务
     */
    public List<InsideMainTaskEntity> getListMainTasks(InsideMainTaskFilter filter)
    {
       // String userId = SysUserUtils.getUserId();
        String roleId = SysUserUtils.getRoleId();
        if("02".equals(roleId)){
            return dao.getListMainTask(filter);
        }

        //先拿到 人员未完成的任务
        InsideUserTaskFilter filter1 = new InsideUserTaskFilter();
        filter1.setTaskState("9");
        filter1.setUserId(SysUserUtils.getUserId());
        List<InsideUserTaskFilter> unDoLists = userTaskService.getUserlist(filter1);
        List<InsideMainTaskEntity> listTasks = new ArrayList<>();
        for (InsideUserTaskFilter item : unDoLists) {
            String mainTaskId = item.getMainTaskId();

            InsideMainTaskEntity byId = dao.getById(mainTaskId);
            listTasks.add(byId);
        }

        return listTasks;

    }

}
